package com.wuming.house.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wuming.house.core.HouseType;
import com.wuming.house.core.JsonResult;
import com.wuming.house.model.House;
import com.wuming.house.model.UserCollection;
import com.wuming.house.model.WeixinUser;
import com.wuming.house.service.HouseService;
import com.wuming.house.service.UserCollectionService;
import com.wuming.house.service.WeixinUserService;
import com.wuming.house.util.EmojiFilter;
import com.wuming.house.util.WechatUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

@Controller
@RequestMapping("/api/my")
public class MyApi {
    private static Logger logger = LoggerFactory.getLogger(MyApi.class);

    @Autowired
    private WeixinUserService weixinUserService;

    @Autowired
    private UserCollectionService userCollectionService;

    @Autowired
    private HouseService houseService;

    /**
     * 微信用户登录详情
     */
    @ResponseBody
    @RequestMapping(value = "/wx/login", method = RequestMethod.POST)
    public JsonResult userLogin(@RequestParam(value = "code", required = false) String code,
                                @RequestParam(value = "rawData", required = false) String rawData,
                                @RequestParam(value = "signature", required = false) String signature,
                                @RequestParam(value = "encrypteData", required = false) String encrypteData,
                                @RequestParam(value = "iv", required = false) String iv) {
        // 用户非敏感信息：rawData
        // 签名：signature
        JSONObject rawDataJson = JSON.parseObject(rawData);
        // 1.接收小程序发送的code
        // 2.开发者服务器 登录凭证校验接口 appi + appsecret + code
        JSONObject SessionKeyOpenId = WechatUtil.getSessionKeyOrOpenId(code);
        // 3.接收微信接口服务 获取返回的参数
        String openid = SessionKeyOpenId.getString("openid");
        String sessionKey = SessionKeyOpenId.getString("session_key");

        // 4.校验签名 小程序发送的签名signature与服务器端生成的签名signature2 = sha1(rawData + sessionKey)
        String signature2 = DigestUtils.sha1Hex(rawData + sessionKey);
        if (!signature.equals(signature2)) {
            return new JsonResult(null, "签名校验失败", false);
        }
        // 5.根据返回的User实体类，判断用户是否是新用户，是的话，将用户信息存到数据库；不是的话，更新最新登录时间
        WeixinUser user = weixinUserService.getUserBySkey("", openid);
        // uuid生成唯一key，用于维护微信小程序用户与服务端的会话
        String skey = UUID.randomUUID().toString();
        if (user == null) {
            // 用户信息入库
            String nickName = rawDataJson.getString("nickName");
            String avatarUrl = rawDataJson.getString("avatarUrl");
            String gender = rawDataJson.getString("gender");
            String city = rawDataJson.getString("city");
            String country = rawDataJson.getString("country");
            String province = rawDataJson.getString("province");
            user = new WeixinUser();
            user.setOpenId(openid);
            user.setSkey(skey);
            user.setCreateTime(new Date());
            user.setLastVisitTime(new Date());
            user.setSessionKey(sessionKey);
            user.setCity(city);
            user.setProvince(province);
            user.setCountry(country);
            user.setAvatarUrl(avatarUrl);
            user.setGender(Integer.parseInt(gender));
            //处理微信昵称中的特殊图片
            nickName = EmojiFilter.filterEmoji(nickName);
            user.setNickname(nickName);
            weixinUserService.saveWeixinUser(user);
        } else {
            // 已存在，更新用户登录时间
            user.setLastVisitTime(new Date());
            // 重新设置会话skey
            user.setSkey(skey);
            weixinUserService.modifyWeixinUser(user);
        }
        //encrypteData比rowData多了appid和openid
        //JSONObject userInfo = WechatUtil.getUserInfo(encrypteData, sessionKey, iv);
        //6. 把新的skey返回给小程序
        JsonResult result = new JsonResult(skey, "登录成功.", true);
        return result;
    }


    /**
     * 根据所属驾校、教练名、手机号查询教练信息
     *
     * @param realname 用户信息
     * @param mobile   用户手机号
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/user/login", method = RequestMethod.GET)
    public JsonResult updateWXUserInfo(String realname, String mobile, @RequestParam(required = false) String age, @RequestParam(required = false) String profession, @RequestParam(required = false) String userAddr, @RequestParam(required = false) String skey) {
        logger.info("用户姓名:{},用户登录态：{}", realname, skey);
        try {
            WeixinUser user = weixinUserService.getUserBySkey(skey, "");
            if (null != user) {
                user.setRealname(realname);
                user.setMobile(mobile);
                user.setAge(age);
                user.setProfession(profession);
                user.setUserAddr(userAddr);
                weixinUserService.modifyWeixinUser(user);
            }
            return new JsonResult(user, "用户登录成功", true);
        } catch (Exception e) {
            logger.error("用户登录失败,失败原因:{}", e.getMessage());
            return new JsonResult(null, "用户登录失败", false);
        }
    }


    /**
     * 根据所属驾校、教练名、手机号查询教练信息
     *
     * @param skey 用户登录态
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public JsonResult logout(@RequestParam(required = false) String skey) {
        logger.info("用户登录态：{}", skey);
        try {
            WeixinUser user = weixinUserService.getUserBySkey(skey, "");
            if (null != user) {
                user.setSkey("-1");
                weixinUserService.modifyWeixinUser(user);
            }
            return new JsonResult(null, "用户登录成功", true);
        } catch (Exception e) {
            logger.error("用户退出失败,失败原因:{}", e.getMessage());
            return new JsonResult(null, "用户退出失败", false);
        }
    }


    /**
     * 根据用戶id查询用户收藏
     *
     * @param userId 用戶id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/collection/get", method = RequestMethod.GET)
    public JsonResult getUserCollection(@RequestParam Long userId) {
        logger.info("用户{}的收藏.", userId);
        Map<String, Object> collectionResult = new HashMap<>();
        List<House> newHouses = new ArrayList<>();
        try {
            List<UserCollection> collectionList = userCollectionService.getUserCollectionById(userId, null, null);
            for (UserCollection uc : collectionList) {
                if (uc.getHouseType().intValue() == HouseType.NEW_HOUSE.getValue().intValue()) {
                    House house = houseService.getHouseById(uc.getHouseId());
                    newHouses.add(house);
                } else {

                }
            }
            collectionResult.put("newHouses", newHouses);
            return new JsonResult(collectionResult, "查询用户收藏成功", true);
        } catch (Exception e) {
            logger.error("查询用户收藏失败,失败原因:{}", e.getMessage());
            return new JsonResult(null, "查询用户收藏失败", false);
        }
    }
}

